package linklist;


import org.junit.Test;

/**
 * @author kunkun
 * @className LeetCode_2
 * @Description ...
 * @date 2025/3/21 15:56
 */
public class LeetCode_2 {

    public class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    @Test
    public void test(){
//        ListNode l1 = new ListNode(2, new ListNode(4, new ListNode(9, null)));
//        ListNode l2 = new ListNode(5, new ListNode(6, new ListNode(4, new ListNode(9,null))));
        ListNode l1 = new ListNode(5, null);
        ListNode l2 = new ListNode(5, null);
        addTwoNumbers(l1,l2);
    }



    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode temp1 = l1,temp2 = l2,result;
        //1.计算各自长度
        int length1 = 0 ,length2=0;
        while (temp1!=null){
            length1++;
            temp1=temp1.next;
        }
        while (temp2!=null){
            length2++;
            temp2=temp2.next;
        }
        if (length1>length2){
            temp1 = l2;
            temp2 = l1;
            result = l1;
        }else {
            temp1 = l1;
            temp2 = l2;
            result = l2;
        }
        //2.汇总相加
        while (temp2!=null && temp1!=null){
            temp2.val = temp1.val +temp2.val;
            temp1=temp1.next;
            temp2=temp2.next;
        }
        //3. 逐个处理
        ListNode temp = new ListNode(),before=null;
        temp = result;
        Boolean flag = false;
        while (temp!=null){
            if (flag){
                temp.val = temp.val+1;
                flag = false;
            }
            if (temp.val>=10){
                flag = true;
                temp.val = temp.val-10;
            }
            before= temp;
            temp = temp.next;
        }
        if (flag){
            before.next = new ListNode(1,null);;
        }
        return result;
    }



}
